package com.tjsinfo.tjsoa.meetingroom.bo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;

import com.tjsinfo.tjsoa.Dao.IHibernateDao;
import com.tjsinfo.tjsoa.Dao.IQbcDao;
import com.tjsinfo.tjsoa.addresslist.bo.IAddressListAndFilePendingBo;
import com.tjsinfo.tjsoa.addresslist.vo.AddressListAndFilePending;
import com.tjsinfo.tjsoa.common.DateTimeFromConver;
import com.tjsinfo.tjsoa.meetingroom.dao.IMeetingRoomEmployDAO;
import com.tjsinfo.tjsoa.meetingroom.dao.IMeetingRoomMainDAO;
import com.tjsinfo.tjsoa.meetingroom.vo.IMeetingRoomEmploy;
import com.tjsinfo.tjsoa.meetingroom.vo.IMeetingRoomMain;
import com.tjsinfo.tjsoa.meetingroom.vo.MeetingRoomEmploy;
import com.tjsinfo.tjsoa.meetingroom.vo.MeetingRoomMain;
import com.tjsinfo.tjsoa.system.bo.ISystemUserBo;
import com.tjsinfo.tjsoa.system.vo.TSystemUser;

public class MeetingRoomEmployBo implements IMeetingRoomEmployBo{
	private IMeetingRoomEmployDAO mred;
	private IMeetingRoomMainDAO mrmd;
	private ISystemUserBo systemUserBo;
	
	private DateTimeFromConver dtfc;
	private TSystemUser user;
	private IQbcDao qbcDao;
	private IAddressListAndFilePendingBo addressListAndFilePendingBo;
	private IHibernateDao hibernateDao;
	
	public IHibernateDao getHibernateDao() {
		return hibernateDao;
	}

	public void setHibernateDao(IHibernateDao hibernateDao) {
		this.hibernateDao = hibernateDao;
	}

	public IQbcDao getQbcDao() {
		return qbcDao;
	}

	public void setQbcDao(IQbcDao qbcDao) {
		this.qbcDao = qbcDao;
	}

	/**
	 * 根据会议室id查找会议室名称
	 * @param 会议室申请状态
	 * @return
	 */
	public List searchRoomId(java.lang.String id)
	{
		try {
			return  mred.findByMeetingRoomId(id);
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 根据会议室id查找会议室名称
	 * @param 会议室申请状态
	 * @return
	 */
	public IMeetingRoomMain findMainRoomId(java.lang.String id)
	{
		try {
			return  mrmd.findById(id);
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 将字符串转成int
	 * @param id
	 * @return
	*/
	public int valueInt(String id){
		int intId=Integer.parseInt(id);
		return intId;
	}
	/**
	 * 根据会议室id查找会议室名称
	 * @param 会议室申请状态
	 * @return
	 */
	public List searchState(String state)
	{
		try {
			return  mred.findByState(state);
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 根据会议室id,年份和月份查询
	 * @param 会议室id
	 * @param 年
	 * @param 月
	 * @return
	*/
	public List searchYearAndMonthAndId(String year,String month,String id)
	{
		try {
			return mred.findByThrProperty("endYear", year, "endMonth", month, "meetingRoomMain.id", id);
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 根据会议室id,年份和月份查询,并转成Map
	 * @param 会议室id
	 * @param 年
	 * @param 月
	 * @return
	*/
	public Map<Date, MeetingRoomEmploy> searchYearAndMonthAndIDMAP(String year,String month,String id)
	{
		Map<Date, MeetingRoomEmploy> map = new HashMap<Date, MeetingRoomEmploy>();
		List list =  searchYearAndMonthAndId(year,month,id);
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			MeetingRoomEmploy mre = (MeetingRoomEmploy) iterator.next();
			map.put(dtfc.datetostr(mre.getMeetingTime()), mre);
		}
		return map;
	}
    
	/**
	 * 保存数据
	 * @param MeetingRoomEmploy
	 * @return
	*/
	public void save(IMeetingRoomEmploy transientInstance){
		try {
			mred.save(transientInstance);
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void save(Object transientInstance){
		try {
			mred.save(transientInstance);
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void delete(Object transientInstance){
		try {
			mred.delete(transientInstance);
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据是否有审核人决定审核状态
	 * @param 审核人id
	 * @return 1为已预定 4为审核中
	*/
	public String selectState(String approvalPeopleId){
		if("".equals(approvalPeopleId)||approvalPeopleId==null){
			return "1";
		}
		return "3";
	}
	/**
	 * 根据审核结果决定审核状态
	 * @param 审核人id
	 * @return 1为已预定 0为拒绝
	*/
	public String results(String result){
		if("1".equals(result)){
			return "1";
		}
		return "0";
	}
	
	/**
	 * 更新数据
	 * @param MeetingRoomEmploy
	 * @return
	*/
	public void update(IMeetingRoomEmploy transientInstance){
		try {
			mred.update(transientInstance);
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	/**
	 * 根据id查询相关的信息
	 * @param id
	 * @return
	*/
	public IMeetingRoomEmploy searchId(String id) {
		try {
			return mred.findById(id);
		} catch (RuntimeException re) {
			throw re;
		}
	}
	/**
	 * 根据传进来的人员ID参数，转换成人员姓名
	 * @param id
	 * @return
	*/
	public StringBuffer IdConversionName(java.lang.String id) {
		StringBuffer name=new StringBuffer();
		String[] arrId=id.split(",");
		for(int i=0;i<arrId.length;i++)
		{
			if(arrId[i]!=null && !"".equals(arrId[i])){
				user=systemUserBo.findByIdSystemUser(this.valueInt(arrId[i]));
				name.append(","+user.getUserName());
			}
		}
		return name;
	}
	/**
	 * 删除
	 * @param id
	 * @return
	*/
	public void delete(IMeetingRoomEmploy transientInstance){
		try {
			mred.delete(transientInstance);
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 判断会议室是否被使用或被预定
	 * @param id
	 * @return
	*/
    public boolean isDelete(java.lang.String id){
    	List list=mred.findByMeetingRoomId(id);
    	if(list.size()>=1){
    		return false;
    	}else{
    		return true;
    	}
    	
    }
	/**
	 * 判断申请日期是否低于当前日期
	 * @param id
	 * @return
	*/
    public boolean isTrueDate(java.lang.String time){
    	    Date date=new Date();
    	    int year=date.getYear()+1900;
        	int month=date.getMonth()+1;
        	int day=date.getDate();
        	int yearS=this.valueInt(time.substring(0, time.indexOf("-")));
        	int monthS=this.valueInt(time.substring(time.indexOf("-")+1,time.lastIndexOf("-")));
        	int dayS=this.valueInt(time.substring(time.lastIndexOf("-")+1));
        	if(yearS<year){
        		return false;
        	}else if(yearS==year && monthS<month){
        		return false;
        	}
        	else if(yearS==year && monthS==month && dayS<day){
        		return false;
        	}else{
        		return true;
        	}
    }
    /**
	 * 判断会议室是否已被使用
	 * @param date
	 * @return
	*/
    public void isUsing(java.util.Date date,java.lang.String id){
    	List roomList=(List)this.searchRoomId(id);
    	int year=date.getYear()+1900;
    	int month=date.getMonth()+1;
    	int day=date.getDate();
    	int hour=date.getHours();
    	int minute=date.getMinutes();
    	int endYear = 0;
    	int endMonth = 0;
    	int endDay = 0;
    	int endHour = 0;
    	int endMinute = 0;
    	for (Iterator iterator = roomList.iterator(); iterator.hasNext();) {
			MeetingRoomEmploy roomEmpoly = (MeetingRoomEmploy) iterator.next();
			MeetingRoomEmploy empoly=(MeetingRoomEmploy)this.searchId(roomEmpoly.getId());
			endHour=roomEmpoly.getStartTime().getHours();
			endMinute = roomEmpoly.getStartTime().getMinutes();
			endDay = roomEmpoly.getStartTime().getDate();
			
			endYear=this.valueInt(roomEmpoly.getEndYear());
			endMonth=this.valueInt(roomEmpoly.getEndMonth());
			if(year>endYear && "1".equals(roomEmpoly.getIsApproval())){
				empoly.setState("2");
	        	this.update(empoly);
			}else if(year==endYear && month>endMonth && "1".equals(roomEmpoly.getIsApproval())){
				empoly.setState("2");
	        	this.update(empoly);
			}else if(year==endYear && month==endMonth && "1".equals(roomEmpoly.getIsApproval())){
				if(day>endDay){
		        	empoly.setState("2");
		        	this.update(empoly);
		        }else if(day==endDay && hour>endHour && "1".equals(roomEmpoly.getIsApproval())){
		        	empoly.setState("2");
		        	this.update(empoly);
		        }
		        else if(day==endDay && hour==endHour && minute>endMinute && "1".equals(roomEmpoly.getIsApproval())){
		        	empoly.setState("2");
		        	this.update(empoly);
		        }  
			}
			
		}
    }
    
    /**
	 * 根据会议室Id和时间查询此会议室是否已使用或以预定,并返回状态值Re_use
	 * @param id
	 * @param date
	 * @return
	*/
    public String searchIdAndDate(java.lang.String id,java.lang.String date){
    	List list=mred.findByIdAndDate("meetingRoomMain.id", id, "startTime", date);
    	if(list.size()>0){
    		return "1";
    	}else{
    		return "0";
    	}
    }
    /**
	 * 根据会议室Id和时间(结束时间)查询此会议室信息
	 * @param id
	 * @param date
	 * @return
	*/
    public List searchReuse(java.lang.String id,java.lang.String date){
    	List list=mred.findByIdAndDate("meetingRoomMain.id", id, "startTime", date);
    	return list;
    }
    /**
	 * 根据会议室Id和时间（开始时间）查询此会议室信息
	 * @param id
	 * @param date
	 * @return
	*/
    public List searchStartTime(java.lang.String id,java.lang.String date){
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	List list = mred.findByIdAndDate("meetingRoomMain.id", id, "startTime", date);
    	return list;
    }
    /**
	 * 查找当前用户是否为申请人
	 * @param 
	 * @param 
	 * @return
	*/
    public boolean isApplicationUser(java.lang.String id,java.lang.String userId){
    	MeetingRoomEmploy mre=(MeetingRoomEmploy)this.searchId(id);
    	if(userId.equals(mre.getApplicationUserId())){
    		return true;
    	}
    	return false;
    }
    /**
	 * 查找是否有多会议室标识(Re_use)
	 * @param 
	 * @param 
	 * @return
	*/
    public List searchIdAndReuse(java.lang.String id){
    	List list=mred.findByProperty("meetingRoomMain.id", id);
    	//List list=mred.findByLikeThrProperty("meetingRoomMain.id", intId, "reUse", "1", propertyName3, time);
    	return list;
    }
    /**
	 * 删除未审批会议申请时做的处理
	 * @param 
	 * @param 
	 * @return
	*/
    public void deleteCopy(String id,java.lang.String time){
    	MeetingRoomEmploy mre=(MeetingRoomEmploy)this.searchId(id);
	    this.delete(mre);
    }
    /**
	 * 查询待审批的列表(发送系统消息用)
	 * @param 
	 * @param 
	 * @return
	*/
    public List searchThr(java.lang.String id){
    	return mred.findByThrProperty("examineUserId", id, "meetingId", "1", "state", "3");
    }
    
    public void jujue(MeetingRoomEmploy empoly,Integer userid,String username) {
		DetachedCriteria criteria = DetachedCriteria.forClass(MeetingRoomEmploy.class);
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		SimpleDateFormat sdf1= new SimpleDateFormat("yyyy-MM-dd"); 
		List list = new ArrayList();
		try {
			java.sql.Date qian = new java.sql.Date(sdf.parse(sdf1.format(empoly.getStartTime())+" 00:00:00").getTime()); 
			java.sql.Date hou = new java.sql.Date(sdf.parse(sdf1.format(empoly.getStartTime())+" 23:59:59").getTime());
			criteria.add(Expression.between("startTime", qian, hou));
			criteria.add(Expression.eq("meetingRoomMain", empoly.getMeetingRoomMain()));
			criteria.add(Expression.eq("state", "3"));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		list=qbcDao.getCriteria(criteria);
    	
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			MeetingRoomEmploy _employ = (MeetingRoomEmploy) iterator.next();
			boolean bl = false;
			if ("全天".equals(empoly.getRemarks())) {
				bl = true;
				_employ.setState("0");
				hibernateDao.update(_employ);
			}else if ("上午".equals(empoly.getRemarks())) {
				if ("全天".equals(_employ.getRemarks()) || "上午".equals(_employ.getRemarks())) {
					bl = true;
					_employ.setState("0");
					hibernateDao.update(_employ);
				}
			}else if ("下午".equals(empoly.getRemarks())) {
				if ("全天".equals(_employ.getRemarks()) || "下午".equals(_employ.getRemarks())) {
					bl = true;
					_employ.setState("0");
					hibernateDao.update(_employ);
				}
			}
			
			if (bl) {
				addressListAndFilePendingBo.deleteByUserIdAndUrl(userid, _employ.getId());
				
				AddressListAndFilePending message2 = new AddressListAndFilePending();
				message2.setId(UUID.randomUUID().toString().replace("-", ""));
				message2.setSendUserId(userid);
				message2.setSendUserName(username);
				message2.setCreateTime(new Date());
				message2.setTjsUserId(Integer.valueOf(_employ.getApplicationUserId()));
				message2.setUrl(_employ.getId());
				message2.setType("会议申请拒绝");
				message2.setTitle("会议申请拒绝");
				addressListAndFilePendingBo.save(message2);
			}
		}
	}
    
	public void setMred(IMeetingRoomEmployDAO mred) {
		this.mred = mred;
	}

	public void setMrmd(IMeetingRoomMainDAO mrmd) {
		this.mrmd = mrmd;
	}

	public void setSystemUserBo(ISystemUserBo systemUserBo) {
		this.systemUserBo = systemUserBo;
	}

	public void setDtfc(DateTimeFromConver dtfc) {
		this.dtfc = dtfc;
	}

	public IAddressListAndFilePendingBo getAddressListAndFilePendingBo() {
		return addressListAndFilePendingBo;
	}

	public void setAddressListAndFilePendingBo(
			IAddressListAndFilePendingBo addressListAndFilePendingBo) {
		this.addressListAndFilePendingBo = addressListAndFilePendingBo;
	}
}
